package com.tanhua.server.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.server.config.AliyunConfig;
import com.tanhua.server.vo.SoundUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * @Author:
 * @Description:  语音文件上传到oss
 * @Date: Created in 16:14 2021/1/17
 * @ModifiedBy:
 */
@Service
public class SoundUploadService {

    //允许上传的格式
    private static final String[] SOUND_TYPE = new String[]{".mp3",".aac",".m4a",".mp2",".wav",".mka"};

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;
    //上傳語音到oss,大小
    public SoundUploadResult upload(MultipartFile soundFile) {
        //创建语音文件上传对象
        SoundUploadResult fileUploadResult = new SoundUploadResult();

        boolean isLegal = false;
        //判断是否为语音文件
        for (String s : SOUND_TYPE) {
            //endsWithIgnoreCase忽略大小写
            if (StringUtils.endsWithIgnoreCase(soundFile.getOriginalFilename(),s)) {
                isLegal = true;
                break;
            }
        }
        //不是语音文件不上传
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            //返回文件上传失败的结果
            return fileUploadResult;
        }

        // 文件新路径
        String fileName = soundFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        //上传到阿里云
        try {
            // 目录结构：sound/2018/12/29/xxxx.jpg
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(soundFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        // 上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setSid(String.valueOf(System.currentTimeMillis()));

        return fileUploadResult;
    }


    //从oss中获取请求地址
    private String getFilePath(String fileName) {

        //创建当前时间对象
        DateTime dateTime = new DateTime();
        return "sound/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                //根据当前时间生成路径
                StringUtils.substringAfterLast(fileName, ".");
    }
}
